import { hex_md5 } from '@/utils/md5';
import { ticket } from '@/constants/system-config';

export const guid = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

export const isEmptyObject = (obj) => {
  if (!obj) { return true }
  for (let key in obj) {
    return false;
  }
  return true;
}

export const getScene = (scene = '') => {
  if (scene == '') return {};
  let res = {};
  let params = decodeURIComponent(scene).split('&');
  params.forEach(item => {
    let pram = item.split('=');
    res[pram[0]] = pram[1];
  });
  return res;
};

export const getParamByName = (url, name) => {
  var url = document.location.href;
  var name = '';
  if (url.indexOf('=') > 0) {
    name = url.substring(url.indexOf('=') + 1, url.length);
  }
  return name;
};

export const getTopOffset = () => {
  const systemInfo = uni.getSystemInfoSync();
  //状态栏高度
  let tophight = systemInfo.statusBarHeight + 'px';
  // 获取胶囊按钮的位置
  const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
  console.log('**********', menuButtonInfo);
  // 导航栏高度 = 状态栏到胶囊的间距（ 胶囊距上距离 - 状态栏高度 ）*2  +  胶囊高度
  let navBarHeight = menuButtonInfo.top + (menuButtonInfo.top - systemInfo.statusBarHeight) + menuButtonInfo.height;
  return navBarHeight;
};

export const parseTime = (time, cFormat) => {
  if (arguments.length === 0) {
    return null;
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
  let date;
  if (typeof time === 'object') {
    date = time;
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000;
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1];
    if (result.length > 0 && value < 10) {
      value = '0' + value;
    }
    return value || 0;
  });
  return time_str;
};

export const formatTime = (time, option) => {
  time = +time * 1000;
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return '刚刚';
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前';
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前';
  } else if (diff < 3600 * 24 * 2) {
    return '1天前';
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分';
  }
};

export const timeFilter = seconds => {
  let ss = Math.floor(seconds); // 秒
  let mm = 0; // 分
  let hh = 0; // 小时
  if (ss > 60) {
    mm = Math.floor(ss / 60);
    ss = Math.floor(ss % 60);
  }
  if (mm > 60) {
    hh = Math.floor(mm / 60);
    mm = Math.floor(mm % 60);
  }

  let result = ('00' + Math.floor(ss)).slice(-2);
  if (mm > 0) result = ('00' + Math.floor(mm)).slice(-2) + ':' + result;
  else result = '00:' + result;

  if (hh > 0) result = ('00' + Math.floor(hh)).slice(-2) + ':' + result;
  return result;
};

export const secToMin = seconds => {
  let ss = Math.floor(seconds); // 秒
  let mm = 0; // 分
  if (ss > 60) {
    mm = Math.floor(ss / 60);
  } else {
    if (ss > 0) {
      mm = 1;
    } else {
      mm = 0;
    }
  }
  return mm;
};

export const secToMinS = seconds => {
  let ss = Math.floor(seconds); // 秒
  let mm = 0; // 分
  let hh = 0; // 小时
  if (ss > 60) {
    if (ss > 3600) {
      hh = Math.floor(ss / 3600);
      ss = Math.floor(ss % 3600);
    }
    mm = Math.floor(ss / 60);
    ss = Math.floor(ss % 60);
  }

  let result = ('00' + Math.floor(ss)).slice(-2);

  if (mm > 0) result = ('00' + Math.floor(mm)).slice(-2) + ':' + result;
  else result = '00:' + result;
  if (hh < 10) result = '0' + hh + ':' + result;
  else result = hh + ':' + result;
  return result;
};

export const CountCharacters = Words => {
  //统计字数
  let _words = Words.replace(/(\s$)/g, ''); //不将右空格计算到里面
  _words = _words.replace(/^(\s*)\r\n/g, ''); //去除空行

  let sTotal = 0; //双字节的字符
  let iTotal = 0; //汉字
  let eTotal = 0; //非双字节的字符
  let iChar = 0; //字母
  let inum = 0; //数字

  for (i = 0; i < _words.length; i++) {
    let c = _words.charAt(i);
    if (c.match(/[\u4e00-\u9fa5]/)) {
      //中文
      iTotal++; //汉字
    }
    if (c.match(/[^\x00-\xff]/)) {
      //双字节的字符
      sTotal++;
    } else {
      eTotal++; //非双字节的字符
    }
    if (c.match(/[a-zA-Z]/)) {
      iChar++; //字母
    }
    if (c.match(/[0-9]/)) {
      inum++; //数字
    }
  }
  // Math.ceil(iTotal + (sTotal - iTotal) + (eTotal - iChar - inum)*0.5 + iChar + inum);
  return Math.ceil(sTotal + eTotal * 0.5);
};

//避免引入新的js包，自己对formate进行简易封装
export function format(fmt) {
  //author: meizz
  var o = {
    'M+': new Date().getMonth() + 1, //月份
    'd+': new Date().getDate(), //日
    'h+': new Date().getHours(), //小时
    'm+': new Date().getMinutes(), //分
    's+': new Date().getSeconds(), //秒
    'q+': Math.floor((new Date().getMonth() + 3) / 3), //季度
    S: new Date().getMilliseconds(), //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (new Date().getFullYear() + '').substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
  return fmt;
}

/**
 * 初始化设备信息
 */
export function initDeviceInfo() {
  let _deviceInfo = ''; //设备信息
  console.log(navigator, 'navigator');
  if (navigator == null) {
    _deviceInfo = 'PC';
  }
  if (navigator.userAgent != null) {
    var su = navigator.userAgent.toLowerCase(),
      mb = ['ipad', 'iphone os', 'midp', 'rv:1.2.3.4', 'ucweb', 'android', 'windows ce', 'windows mobile'];

    // 开始遍历提前设定好的设备关键字，如果设备信息中包含关键字，则说明是该设备
    for (var i in mb) {
      if (su.indexOf(mb[i]) > 0) {
        _deviceInfo = mb[i];
        break;
      }
    }
  }
  return _deviceInfo;
}

/**
 * 获取浏览器的信息
 */
export function getBrowserInfo() {
  var output = 'other';
  // Opera 8.0+
  var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
  if (isOpera) {
    output = 'Opera';
  }
  // Firefox 1.0+
  var isFirefox = typeof InstallTrigger !== 'undefined';
  if (isFirefox) {
    output = 'Firefox';
  }
  // Safari 3.0+ "[object HTMLElementConstructor]"
  var isSafari =
    /constructor/i.test(window.HTMLElement) ||
    (function (p) {
      return p.toString() === '[object SafariRemoteNotification]';
    })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification));
  if (isSafari) {
    output = 'Safari';
  }
  // Internet Explorer 6-11
  var isIE = /*@cc_on!@*/ false || !!document.documentMode;
  if (isIE) {
    output = 'IE';
  }
  // Edge 20+
  var isEdge = !isIE && !!window.StyleMedia;
  if (isEdge) {
    output = 'Edge';
  }
  // Chrome 1 - 79
  var isChrome = !!window.chrome && navigator.userAgent.indexOf('Chrome') !== -1;
  if (isChrome) {
    output = 'Chrome';
  }
  // Edge (based on chromium) detection
  var isEdgeChromium = isChrome && navigator.userAgent.indexOf('Edg') !== -1;
  if (isEdgeChromium) {
    output = 'EdgeChromium';
  }
  return output;
}

export function detectOS() {
  var userAgent = window.navigator.userAgent,
    platform = window.navigator.platform,
    macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'],
    windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'],
    iosPlatforms = ['iPhone', 'iPad', 'iPod'],
    os = null;

  if (macosPlatforms.indexOf(platform) !== -1) {
    os = 'Mac OS';
  } else if (iosPlatforms.indexOf(platform) !== -1) {
    os = 'iOS';
  } else if (windowsPlatforms.indexOf(platform) !== -1) {
    os = 'Windows';
  } else if (/Android/.test(userAgent)) {
    os = 'Android';
  } else if (!os && /Linux/.test(platform)) {
    os = 'Linux';
  }

  return os;
}

export function digits() {
  var sUserAgent = navigator.userAgent;
  var is64 = sUserAgent.indexOf('WOW64') > -1;
  if (is64) {
    return '64bit';
  } else {
    return '32bit';
  }
}

/**
 * 处理富文本里的图片宽度自适应
 * 1.去掉img标签里的style、width、height属性
 * 2.img标签添加style属性：max-width:100%;height:auto
 * 3.修改所有style里的width属性为max-width:100%
 * 4.去掉<br/>标签
 * @param html
 * @returns {void|string|*}
 */
export function formatRichText(html = '') {
  let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
    return match;
  });
  newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
    match = match.replace(/font-size:[^;]+;/gi, '').replace(/color:[^;]+;/gi, '')
    match = match.replace(/width:[^;]+;/gi, 'max-width:100%;')
    return match;
  });
  newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  newContent = newContent.replace(
    /\<img/gi,
    '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"'
  );
  return newContent;
}

// 获取输入框中的字符串的字节长度
export function getByteLength(val) {
  let str = new String(val);
  let bytesCount = 0;
  for (let i = 0, n = str.length; i < n; i++) {
    let c = str.charCodeAt(i);
    if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
      bytesCount += 1;
    } else {
      bytesCount += 2;
    }
  }
  return bytesCount;
}

/**
 * 上传文件
 * @param {string} filePath 要上传文件资源的路径 (本地路径)
 * @returns Promise 服务器中文件的资源地址
 */
export function uploadFileAsync(filePath) {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: process.env.VUE_APP_BASE_API + '/api/v1/wechat/applet/upload_file', // 开发者服务器地址
      filePath, // 要上传文件资源的路径 (本地路径)
      name: 'file', // 文件对应的 key，开发者在服务端可以通过这个 key 获取文件的二进制内容
      formData: {}, // HTTP 请求中其他额外的 form data
      header: {
        Authorization: uni.getStorageSync('token'),
        Sign: hex_md5(ticket),
      },
      success: res => {
        console.log('------updload file----', res);
        if (res.statusCode != 200) {
          reject(res.data);
        } else {
          res.data = typeof res.data == 'string' ? JSON.parse(res.data) : res.data;
          if (res.data.error != 0) {
            reject(res.data);
          } else {
            resolve(res.data.data.url);
          }
        }
      },
      fail: err => {
        reject(err);
        console.log('----update-fail----', err);
      },
    });
  });
}
